﻿using System;
using System.Activities;
using System.Collections.Generic;
using Reactor.Environment;
using Reactor.Messages.Events.Adoptions;
using Reactor.Messaging;
using Reactor.Workflow.Extensions;

namespace Reactor.ServiceGrid.Workflows.Activities
{
    public class PrepareToSendAdoptedEvent : CodeActivity
    {
        [RequiredArgument]
        public InArgument<ServiceIdentifier> ServiceIdentifier { get; set; }

        [RequiredArgument]
        public InArgument<Guid> ServiceInstanceIdentifier { get; set; }

        public OutArgument<IEnumerable<IMessagingChannel>> Destinations { get; set; }

        public OutArgument<ServiceAdopted> AdoptedEvent { get; set; }

        protected override void Execute(CodeActivityContext context)
        {
            // Construct message
            var serviceIdentifier = context.GetValue(ServiceIdentifier);
            var coreName = Context.GridContext.CurrentReactorService.Identifier.Name;
            var details = string.Format("Service: {0} adopted by Core: {1}", serviceIdentifier, coreName);
            var msg = new ServiceAdopted
            {
                CoreName = coreName,
                ServiceName = serviceIdentifier.Name,
                Version = serviceIdentifier.Version.ToString(),
                ServiceInstanceIdentifier = context.GetValue(ServiceInstanceIdentifier),
                Subject = details,
                Description = details
            };
            context.SetValue(AdoptedEvent, msg);

            // Check to see if we need to send this message directly to a donor core
            var ext = context.GetExtension<PersistedPropertiesExtension>();
            if (ext == null) return;

            var donorCoreName = ext.GetPersistedPropertyValue<string>(context.WorkflowInstanceId, "TransferWorkflow.DonorCoreName");
            if(!string.IsNullOrEmpty(donorCoreName))
            {
                var destinationChannels = new List<IMessagingChannel> {new PointToPointChannel(donorCoreName)};

                context.SetValue(Destinations, destinationChannels);
            }
        }
    }
}
